import Axios from "axios";
import localDb from "../utils/localDb";
import { Message } from "element-ui";
import router from "../router";
// 如果请求话费了超过 `fetchTimeout` 的时间，请求将被中断
const fetchTimeout = 3000;
// 跨域请求时是否需要使用凭证(携带cookie时需开启)
const withCredentials = false;
let defaultHost;
// let protocol = window.location.protocol; //协议
// let host = window.location.host; //主机+端口

// if (process.env.NODE_ENV === "production") {
//   //defaultHost = protocol + "//" + host;
//   defaultHost = "https://192.168.20.124:8001"
// } else {
//   defaultHost = "/api";
// }
// defaultHost = "https://192.168.20.124:8001";
defaultHost = "http://116.63.40.197:8092"
// defaultHost = "http://222.80.229.14:82"
// defaultHost = 'http://36.107.231.103:85'
// defaultHost = 'http://rxfw.cjzedu.cn:82'
// defaultHost = 'http://36.108.168.87:85'
// defaultHost = "http://bmht.xjktedu.com:81"
// defaultHost = "http://116.63.223.45:8090"

/* ----------------Axios-------------------- */
const server = Axios.create({
  baseURL: defaultHost,
  timeout: fetchTimeout,
  withCredentials: withCredentials
});

// 添加请求拦截器
server.interceptors.request.use(
  config => {
    // 在发送请求之前做些什么
    let token = localDb.get("TOKEN");
    let upload = localDb.get("upload");
    if (token) {
      token = "bearer" + " " + token.replace(/'|"/g, ""); //添加token
      config.headers.common["Authorization"] = token;
    }
    if (upload) {
      config.headers.common["Content-Type"] = "multipart/form-data";
    } else {
      config.headers.common["Content-Type"] = "application/json; charset=utf-8";
    }
    return config;
  },
  error => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
server.interceptors.response.use(
  response => {
    // console.log(response);
    // 对响应数据做点什么\
    //console.log(response.status === 200);
    if (response.status === 200) {
      //console.log(response.headers["content-type"].includes);
      // 如果返回是文件二进制流， 提取文件名 返回 二进制流
      if (response.headers["content-type"].includes("application/data")) {
        const attachment = response.headers["content-disposition"].split(
          "filename="
        );
        const fileName = attachment ? decodeURIComponent(attachment[1]) : "";
        response.data = {
          fileName: fileName,
          blob: response.data
        };
      }
      return Promise.resolve(response.data);
    } else {
      return Promise.reject(response.data);
    }
  },
  error => {
    // 对响应错误做点什么
    // console.log(error.response);
    if (error && error.response) {
      // 无权限
      if (error.response.status === 401) {
        Message({
          message: "登录超时，请重新登录",
          type: "error",
          duration: 4 * 1000
        });
        // 清除TOKEN

        // 跳转页面
        router.replace({
          path: "zmkm",
          query: { redirect: router.currentRoute.fullPath }
        });
      } else if (error.response.status >= 500) {
        router.push({ path: "/error", query: { statusCode: error.response.status } })
      } else {
        // Message({
        //     message:error.response.data.errors[Object.keys(error.response.data.errors)[0]][0],
        //     type:'error',
        //     duration: 4*1000
        // })
      }
    }
    return Promise.reject(error);
  }
);

/**
 *
 * @param {String} url 请求地址
 * @param {Object} data 请求体
 * @param {String} method 请求方法
 */
const fetch = (url, data = {}, method = "get") => {
  if (method.toLowerCase() === "get") {
    return server({
      url: url,
      method: method,
      params: data
    });
  } else if (method.toLowerCase() === "post") {
    return server({
      url: url,
      method: method,
      data: data
    });
  }
};

const install = Vue => (Vue.prototype.$fetch = fetch);
export default { install, fetch, defaultHost };
